﻿using Callisto.Controls;
using Dynamics.NAV.Metro.Common;
using Dynamics.NAV.Metro.Data;
using Okra.Core;
using Okra.Navigation;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Windows.UI.Xaml;

namespace Dynamics.NAV.Metro.Pages.Home
{
    public class HomeViewModel : BindableBase
    {
        private HomeGroup _financeGroup;
        private HomeGroup _receivableGroup;
        private HomeGroup _payablesGroup;
        private HomeGroup _warehouseGroup;

        private HomeItem _chartOfAccounts;
        private HomeItem _bankAccounts;
        private HomeItem _customers;
        private HomeItem _salesQuotes;
        private HomeItem _salesOrders;
        private HomeItem _vendors;
        private HomeItem _purchaseQuotes;
        private HomeItem _purchaseOrders;
        private HomeItem _items;

        private DispatcherTimer _timer;

        private IDynamicsNavApi _navApi;

        public HomeViewModel()
        {
            this.GoBackCommand = new DelegateCommand(GoBack);
            CreateGroups();
        }

        [ImportingConstructor]
        public HomeViewModel(IDynamicsNavApi navApi)
        {
            _navApi = navApi;

            this.GoBackCommand = new DelegateCommand(GoBack);
            CreateGroups();
            StartTimer();
        }

        public ICommand GoBackCommand { get; private set; }

        [Import]
        public INavigationManager NavigationManager { get; set; }

        public IList<NavCompany> Companies
        {
            get { return _navApi.Companies; }
        }

        public NavCompany CurrentCompany
        {
            get { return _navApi.CurrentCompany; }
            set
            {
                _navApi.CurrentCompany = value;
                SettingsStorage.SetLocalSetting(App.DEFAULT_COMPANY_KEY, value.Name);
                AsyncHelpers.RunSync(() => LocalStorage.Save());
            }
        }

        public bool CanGoBack
        {
            get { return NavigationManager.CanGoBack; }
        }

        public void GoBack()
        {
            NavigationManager.GoBack();
        }

        public void NavigateToPage(string pageName, object arguments)
        {
            NavigationManager.NavigateTo(pageName, arguments);
        }

        private void CreateGroups()
        {
            _financeGroup = new HomeGroup("1", "Finance", "Financial Management", "FinancialsOverview", "Assets/LightGray.png");
            _chartOfAccounts = new HomeItem("1", "Accounts", "Chart Of Accounts", "GLAccounts", "Assets/DarkGray.png", _financeGroup);
            _financeGroup.Items.Add(_chartOfAccounts);
            _bankAccounts = new HomeItem("2", "Cash", "Bank Accounts", "BankAccounts", "Assets/DarkGray.png", _financeGroup);
            _financeGroup.Items.Add(_bankAccounts);
            _itemGroups.Add(_financeGroup);

            _receivableGroup = new HomeGroup("2", "Receivables", "Sales & Receivables", "ReceivableOverview", "Assets/LightGray.png");
            _customers = new HomeItem("1", "Customers", "Customer Accounts", "Customers", "Assets/DarkGray.png", _receivableGroup);
            _receivableGroup.Items.Add(_customers);
            _salesQuotes = new HomeItem("2", "Quotes", "Open Sales Quotes", "SalesQuotes", "Assets/DarkGray.png", _receivableGroup);
            _receivableGroup.Items.Add(_salesQuotes);
            _salesOrders = new HomeItem("3", "Orders", "Open Sales Orders", "SalesOrders", "Assets/DarkGray.png", _receivableGroup);
            _receivableGroup.Items.Add(_salesOrders);
            _itemGroups.Add(_receivableGroup);

            _payablesGroup = new HomeGroup("3", "Payables", "Purchase & Payables", "PayablesOverview", "Assets/LightGray.png");
            _vendors = new HomeItem("1", "Vendors", "Vendor Accounts", "Vendors", "Assets/DarkGray.png", _payablesGroup);
            _payablesGroup.Items.Add(_vendors);
            _purchaseQuotes = new HomeItem("2", "Quotes", "Open Purchase Quotes", "PurchaseQuotes", "Assets/DarkGray.png", _payablesGroup);
            _payablesGroup.Items.Add(_purchaseQuotes);
            _purchaseOrders = new HomeItem("3", "Orders", "Open Purchase Orders", "PurchaseOrders", "Assets/DarkGray.png", _payablesGroup);
            _payablesGroup.Items.Add(_purchaseOrders);
            _itemGroups.Add(_payablesGroup);

            _warehouseGroup = new HomeGroup("4", "Warehouse", "Warehouse", "WarehouseOverview", "Assets/LightGray.png");
            _items = new HomeItem("1", "Items", "Items", "Items", "Assets/DarkGray.png", _warehouseGroup);
            _warehouseGroup.Items.Add(_items);
            _itemGroups.Add(_warehouseGroup);
        }

        private void StartTimer()
        {
            if (_timer == null)
            {
                _timer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(1) };
                _timer.Tick += timer_Tick;
                _timer.Interval = TimeSpan.FromSeconds(10);
            }
            _timer.Start();
        }

        private void StopTimer()
        {
            if (_timer != null)
            {
                if (_timer.IsEnabled)
                    _timer.Stop();
            }
        }

        private void timer_Tick(object sender, object e)
        {
            StopTimer();
            UpdateLiveTiles();
            StartTimer();
        }

        private void UpdateLiveTiles()
        {
            //_chartOfAccounts.LiveTileData.Clear();
            //_chartOfAccounts.LiveTileData.Add(new LiveTileData() { Name = "Cash Account", Description = string.Format("Customer Count {0}",1), ImageUri = new Uri("ms-appx:///Assets/DarkGray.png") });
            //_chartOfAccounts.LiveTileData.Add(new LiveTileData() { Name = "COA 2", Description = "Test ", ImageUri = new Uri("ms-appx:///Assets/LightGray.png") });

            //_bankAccounts.LiveTileData.Clear();
            //_bankAccounts.LiveTileData.Add(new LiveTileData() { Name = "Bank", Description = "Test Bank", ImageUri = new Uri("ms-appx:///Assets/LightGray.png") });
            //_bankAccounts.LiveTileData.Add(new LiveTileData() { Name = "Bank 2", Description = "Test Bank 2", ImageUri = new Uri("ms-appx:///Assets/DarkGray.png") });
        }

        private ObservableCollection<HomeGroup> _itemGroups = new ObservableCollection<HomeGroup>();
        public ObservableCollection<HomeGroup> ItemGroups
        {
            get { return this._itemGroups; }
        }

        public HomeGroup GetGroup(string uniqueId)
        {
            // Simple linear search is acceptable for small data sets
            var matches = this.ItemGroups.Where((group) => group.UniqueId.Equals(uniqueId));
            if (matches.Count() == 1) return matches.First();
            return null;
        }

        public HomeItem GetItem(string uniqueId)
        {
            // Simple linear search is acceptable for small data sets
            var matches = this.ItemGroups.SelectMany(group => group.Items).Where((item) => item.UniqueId.Equals(uniqueId));
            if (matches.Count() == 1) return matches.First();
            return null;
        }
    }
}
